<template>
  <div class="captcha-container" v-if="showCaptcha">
    <div class="captcha-input-group">
      <!-- 验证码输入框 -->
      <el-input
        v-model="captchaCode"
        placeholder="请输入验证码"
        size="large"
        maxlength="4"
        :disabled="loading"
        @keyup.enter="$emit('submit')"
        class="captcha-input"
      />
      
      <!-- 验证码图片 -->
      <div class="captcha-image-wrapper" @click="refreshCaptcha" :class="{ 'loading': loading }">
        <img
          v-if="captchaImage"
          :src="captchaImage"
          alt="验证码"
          class="captcha-image"
        />
        <div v-else class="captcha-placeholder">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
        
        <!-- 刷新提示 -->
        <div class="refresh-hint">
          <el-icon><Refresh /></el-icon>
        </div>
      </div>
    </div>
    
    <!-- 验证码说明 -->
    <div class="captcha-hint">
      <el-icon><InfoFilled /></el-icon>
      <span>点击验证码图片可刷新</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading, Refresh, InfoFilled } from '@element-plus/icons-vue'
import { authApi } from '@/api/auth'

// Props
interface Props {
  username: string
  modelValue: string
  sessionId: string
  required: boolean
}

const props = withDefaults(defineProps<Props>(), {
  username: '',
  modelValue: '',
  sessionId: '',
  required: false
})

// Emits
interface Emits {
  (e: 'update:modelValue', value: string): void
  (e: 'update:sessionId', value: string): void
  (e: 'update:required', value: boolean): void
  (e: 'submit'): void
}

const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const captchaImage = ref('')
const captchaRequired = ref(false)

// 计算属性
const captchaCode = computed({
  get: () => props.modelValue,
  set: (value: string) => emit('update:modelValue', value.toUpperCase())
})

const showCaptcha = computed(() => {
  return captchaRequired.value
})

// 方法
const getCaptcha = async () => {
  loading.value = true
  
  try {
    const response = await authApi.getCaptcha()
    
    if (response.success) {
      const { session_id, captcha_image } = response.data
      
      captchaImage.value = captcha_image
      emit('update:sessionId', session_id)
      
      // 清空之前的验证码输入
      emit('update:modelValue', '')
    } else {
      ElMessage.error(response.message || '获取验证码失败')
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
    ElMessage.error('验证码服务异常')
  } finally {
    loading.value = false
  }
}


// 组件挂载时直接显示验证码
const initCaptcha = async () => {
  captchaRequired.value = true
  emit('update:required', true)
  await getCaptcha()
}

const refreshCaptcha = async () => {
  if (loading.value || !showCaptcha.value) {
    return
  }
  
  await getCaptcha()
}

// 初始化验证码
initCaptcha()

// 暴露方法给父组件
defineExpose({
  refresh: refreshCaptcha,
  getCaptcha
})
</script>

<style scoped>
.captcha-container {
  margin-top: 16px;
}

.captcha-input-group {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-input {
  flex: 1;
}

.captcha-image-wrapper {
  position: relative;
  width: 120px;
  height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s ease;
  background: #f5f7fa;
}

.captcha-image-wrapper:hover {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}


.captcha-image-wrapper.loading {
  cursor: not-allowed;
  opacity: 0.6;
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
}

.captcha-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 12px;
}

.loading-icon {
  animation: rotate 1s linear infinite;
  margin-bottom: 4px;
}


.captcha-hint {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.captcha-hint .el-icon {
  font-size: 14px;
}

.refresh-hint {
  position: absolute;
  top: 2px;
  right: 2px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 2px;
  padding: 2px;
  font-size: 10px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.captcha-image-wrapper:hover .refresh-hint {
  opacity: 1;
}

.captcha-hint {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.captcha-hint .el-icon {
  font-size: 14px;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 480px) {
  .captcha-input-group {
    flex-direction: column;
    gap: 8px;
  }
  
  .captcha-image-wrapper {
    width: 100%;
    max-width: 200px;
    align-self: center;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .captcha-image-wrapper {
    border-color: #4c4d4f;
    background: #262727;
  }
  
  .captcha-image-wrapper:hover {
    border-color: #409eff;
  }
  
  .captcha-placeholder {
    color: #a3a6ad;
  }
  
  .captcha-hint {
    color: #a3a6ad;
  }
}
</style>